<template>
  <div class="upload-vr-file">
    <div class="top pd20">
      <!-- 上传附件 -->
      <el-upload
        class="upload-demo upload-card"
        v-model:file-list="imgFileList"
        ref="uploadImg"
        :show-file-list="true"
        multiple
        list-type="picture-card"
        :auto-upload="false"
        :on-change="
          (file, fileList) => {
            handleAvatarChangeIcon(file, fileList, 'file');
          }
        "
      >
        <div style="display: flex; flex-direction: column; align-items: center; color: #86909c">
          <el-icon class="f24"><Plus /></el-icon>
          <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
        </div>

        <template #file="{ file }">
          <div class="jzt-flex-center" style="width: 100%; min-width: 80px">
            <template v-if="file.file">
              <video v-if="['mp4'].includes(getFileSuffix(file.file))" controls style="width: 125px; height: 100%">
                <source :src="file.file" type="video/mp4" />
                对不起，您的浏览器不支持播放视频文件
              </video>
              <el-image
                v-else
                class="el-upload-list__item-thumbnail"
                :src="getUrl(file.file)"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[getUrl(file.file)]"
                fit="cover"
                style="width: 80px; height: 100%"
              />
            </template>

            <span v-show="!file.file" class="f30">
              <el-icon><Loading /></el-icon>
            </span>
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
      <p class="f12" style="color: #86909c">可上传多个视频、图片、VR、以更好的形态展示在用户面前</p>
    </div>
    <div class="bottom pd20">
      <p class="f14 mb6" style="color: #4e5969">VR链接</p>
      <div class="vr-list">
        <div class="vr-item mb10 jzt-flex-bt" v-for="(item, index) in vrList.filter(item => item.delTag === 0)" :key="index">
          <el-upload
            class="VR-uploader"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon2(item, 'liveUrl', file, fileList);
              }
            "
          >
            <div class="upload-wrap">
              <template v-if="item.liveUrl">
                <img :src="item.liveUrl" class="td-img" />
                <div class="mask">
                  <el-icon style="color: white"> <RefreshRight /> </el-icon>重新上传
                </div>
                <!-- <div class="del-icon" @click.stop="delImg('liveUrl')">+</div> -->
              </template>
              <div
                v-else
                :class="{ notuse: FileList.length >= 9 ? true : false }"
                style="display: flex; flex-direction: column; align-items: center; color: #86909c"
              >
                <el-icon class="f24"><Plus /></el-icon>
                <p class="f12" style="line-height: 22px; color: #86909c">上传封面</p>
              </div>
            </div>
          </el-upload>

          <el-input class="ml20" v-model="item.vrUrl" placeholder="请输入VR链接"></el-input>

          <span class="ml10 mr10" style="display: inline-block" @click="delLinkVR(item, index)">
            <img
              src="@/assets/images/del.png"
              alt=""
              style="width: 16px; height: 16px; cursor: pointer; vertical-align: middle"
            />
          </span>
        </div>
      </div>
      <div class="add-btn">
        <el-button class="pl20" link type="primary" @click="addLinkVR">
          <el-icon class="mr10"><CirclePlusFilled /></el-icon>新增链接
        </el-button>
      </div>
      <!-- <el-button @click="getFileData">获取文件列表</el-button> -->
    </div>

    <!-- 移除二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenRemove"
      :title="'提醒'"
      :message="'您正在操作删除实拍文件，为了避免误删除，当前删除只是移除，需要提交发布商品后正式删除文件，请根据需要进行操作！'"
      :submitBtnText="'继续'"
      @submit="returnSubmitRemove"
      @cancel="returnCancelRemove"
    />

    <!-- 移除Vr链接二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenRemoveVr"
      :title="'提醒'"
      :message="'您正在操作删除VR链接，为了避免误删除，当前删除只是移除，需要提交发布商品后正式删除文件，请根据需要进行操作！'"
      :submitBtnText="'继续'"
      @submit="returnSubmitRemoveVr"
      @cancel="returnCancelRemoveVr"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import {
  getFileName,
  getFileSuffix,
  getFileNameByUrl,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import excel from "@/assets/images/excel.png";
import word from "@/assets/word.png";
import pdf from "@/assets/pdf.png";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";

const props = defineProps({
  fileDetailList: {
    type: Array,
    default: () => [] //实拍图回显列表
  },
  vrDetailList: {
    type: Array,
    default: () => [] //vr链接回显列表
  }
});

const FileList = ref([]); //商品图片list
const imgFileList = ref([]); //编辑时商品图片list

const vrList = ref([]);
const _isOpenRemove = ref(false);
const _isOpenRemoveVr = ref(false);
const isInit = ref(1);
const isInitVr = ref(1);

watch(
  () => props.fileDetailList,
  val => {
    if (val) {
      //实拍图回显
      console.log("实拍图回显", val);
      imgFileList.value = val?.map(item => {
        return {
          url: item.liveUrl,
          file: item.liveUrl,
          // uid: "111",
          name: getFileNameByUrl(item.liveUrl)
        };
      });
      FileList.value = imgFileList.value;
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => props.vrDetailList,
  val => {
    if (val) {
      // vr链接回显
      console.log("vr链接回显", val);
      vrList.value = val?.map(item => {
        return {
          liveUrl: item.liveUrl,
          vrUrl: item.vrUrl,
          liveType: item.liveType,
          delTag: item.delTag
        };
      });
    }
  },
  { deep: true, immediate: true }
);

const currentObjVr = ref({});
const returnSubmitRemoveVr = () => {
  isInitVr.value++;
  delLinkVR(currentObjVr.value, currentObjVr.value._index);
  _isOpenRemoveVr.value = false;
};

const returnCancelRemoveVr = () => {
  _isOpenRemove.value = false;
};

const addLinkVR = () => {
  vrList.value.push({ delTag: 0 });
};

const delLinkVR = (item, index) => {
  currentObjVr.value = { ...item, _index: index };
  if (isInitVr.value === 1) {
    _isOpenRemoveVr.value = true;
    return;
  }
  vrList.value.splice(index, 1);
};

const getFileData = () => {
  const imgOrVideoArr = imgFileList.value?.map(item => {
    return {
      liveUrl: item.file,
      vrUrl: "",
      liveType: getFileSuffix(item.file) === "mp4" || getFileSuffix(item.file) === "MP4" ? 2 : 1 //类型;1:图片 2:视频 3：VR
    };
  });
  // console.log("上传的实拍图文件===", imgOrVideoArr);

  const vrArr = vrList.value?.map(item => {
    return {
      liveUrl: item.liveUrl,
      vrUrl: item.vrUrl,
      liveType: 3, //类型;1:图片 2:视频 3：VR
      delTag: item.delTag
    };
  });
  // console.log("VR链接===", vrArr);
  return { imgOrVideoArr, vrArr };
};

const getUrl = url => {
  const fileArr = ["doc", "docx"];
  const excelArr = ["xls", "xlsx"];
  const fileSuffix = getFileSuffix(url).toLowerCase() || "";
  const type = fileArr.includes(fileSuffix)
    ? "doc"
    : excelArr.includes(fileSuffix)
      ? "excel"
      : fileSuffix === "pdf"
        ? "pdf"
        : fileSuffix === "dwg"
          ? "cad"
          : "img";
  return type === "doc" ? word : type === "excel" ? excel : type === "pdf" ? pdf : url;
};
//=====================================================

const handleAvatarChangeIcon2 = (vrItem, key, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    vrItem[key] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload2(vrItem, key, { file }); //调用上传文件api接口
  }
};

const customUpload2 = async (vrItem, key, option) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      vrItem[key] = res.fileUrl.split("?")[0];
      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//====================================图片上传========================================================================================
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { imgsUpload } from "@/api/products/specifications";
import { ElMessage } from "element-plus";

const uploadImg = ref();
const uploadVideo = ref();
const videoList = ref([]); //商品视频list
const videoListEdit = ref([]); //编辑时商品视频list
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, _fileList);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传jpeg，jpg，png图片文件，大小不超过5M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    } else if (type === "video") {
      ElMessage({
        message: "只能上传视频文件，并且视频时长不超过45秒，大小不超过100M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "video/mp4") || item.raw.size > 1024 * 1024 * 100) {
          console.log(111, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          errorFile.push(item);
        } else {
          console.log(222, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadVideo.value.handleRemove(item);
      }
    } else if (type === "file") {
      ElMessage({
        message: "支持上传图片、视频等格式",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png" || item.raw.type === "video/mp4")) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }

    fileList = successFile;
    if (successFile.length <= 0) return;
  }
  //   imgIsReady.value = false;
  if (type === "img" || type === "file") {
    FileList.value = fileList;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  } else {
    videoList.value = fileList;

    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.raw.type === "image/jpeg" || item.raw.type === "image/png") && item.raw.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      // console.log("视频的大小===", item.raw.size);
      if (!(item.raw.type === "video/mp4" && item.raw.size <= 1024 * 1024 * 200)) {
        flag = false;
      }
      //   if (item.raw.type === "video/mp4") {
      //     await getTimes(item.raw);
      //     // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
      //     if (!(videoTime.value <= 45)) {
      //       flag = false;
      //     }
      //   }
    }
  } else if (type === "file") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png" || item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  }
  return flag;
};

const currentObj = ref({});
const returnSubmitRemove = () => {
  isInit.value++;
  handleRemove(currentObj.value);
  _isOpenRemove.value = false;
};

const returnCancelRemove = () => {
  _isOpenRemove.value = false;
};

const handleRemove = (file, type = "img") => {
  console.log("移除===", file);
  currentObj.value = file;
  if (isInit.value === 1) {
    _isOpenRemove.value = true;
    return;
  }
  if (type === "img") {
    uploadImg.value.handleRemove(file);
    FileList.value = FileList.value.filter(item => item.uid !== file.uid);
  } else {
    uploadVideo.value.handleRemove(file);
    videoList.value = videoList.value.filter(item => item.uid !== file.uid);
  }
};

const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  console.log(111111, option, option.file.name);
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      } else if (type === "video") {
        item["video"] = res.fileUrl.split("?")[0];
      } else {
        item["file"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

defineExpose({ getFileData });
</script>

<style lang="scss" scoped>
p {
  padding: 0;
  margin: 0;
}
:deep(.el-image) {
  border-radius: 6px;
}
:deep(.upload-demo) {
  .el-upload-list--picture-card .el-upload-list__item {
    width: auto !important;
  }
}
:deep(.el-upload.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}
.upload-vr-file {
  width: 62%;
  border: 1px solid #e1e6ed;
  border-radius: 4px;
  .top {
    border-bottom: 1px solid #e1e6ed;
  }
  .upload-wrap {
    margin-top: 3px;
    position: relative;
    // height: 100%;
    .del-icon {
      position: absolute;
      color: white;
      width: 10px;
      height: 10px;
      border: 2px solid white;
      background-color: red;
      top: 4px;
      right: -4px;
      border-radius: 50%;
      line-height: 10px;
      transform: rotate(45deg);
    }
    .mask {
      display: none;
    }
    &:hover {
      .mask {
        position: absolute;
        top: 8px;
        left: 0;
        right: 0;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: white;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        transition: all 0.5s;
      }
    }

    img {
      width: 78px;
      height: 78px;
      border-radius: 6px;
      margin-top: 8px;
    }
  }
  .add-btn {
    width: 100%;
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    display: flex;
    align-items: flex-end;
    .el-button {
      width: 100%;
      height: 30px;
      line-height: 30px;
      justify-content: flex-start;
    }
  }
  .vr-list {
    ::-webkit-input-placeholder {
      /* WebKit, Blink, Edge */
      font-size: 12px;
    }
    :-moz-placeholder {
      /* Mozilla Firefox 4 to 18 */
      font-size: 12px;
    }
    ::-moz-placeholder {
      /* Mozilla Firefox 19+ */
      font-size: 12px;
    }
    :-ms-input-placeholder {
      /* Internet Explorer 10-11 */
      font-size: 12px;
    }
  }
}
</style>
